package com.rickpan.repository;

import com.rickpan.entity.Note;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 便签数据访问层
 * 
 * @author RickPan Team
 * @since 2024-01-06
 */
@Repository
public interface NoteRepository extends JpaRepository<Note, Long> {

    /**
     * 根据用户ID查找便签（分页）
     */
    Page<Note> findByUserIdAndIsDeletedFalseOrderByUpdatedAtDesc(Long userId, Pageable pageable);

    /**
     * 根据用户ID和文件夹ID查找便签（分页）
     */
    Page<Note> findByUserIdAndFolderIdAndIsDeletedFalseOrderByUpdatedAtDesc(Long userId, Long folderId, Pageable pageable);

    /**
     * 根据用户ID查找根目录便签（folderId为null）
     */
    Page<Note> findByUserIdAndFolderIdIsNullAndIsDeletedFalseOrderByUpdatedAtDesc(Long userId, Pageable pageable);

    /**
     * 根据用户ID和标题搜索便签
     */
    @Query("SELECT n FROM Note n WHERE n.userId = :userId AND n.isDeleted = false AND " +
           "(n.title LIKE %:keyword% OR n.content LIKE %:keyword% OR n.markdownContent LIKE %:keyword%) " +
           "ORDER BY n.updatedAt DESC")
    Page<Note> searchNotes(@Param("userId") Long userId, @Param("keyword") String keyword, Pageable pageable);

    /**
     * 根据用户ID查找收藏的便签
     */
    Page<Note> findByUserIdAndIsFavoriteTrueAndIsDeletedFalseOrderByUpdatedAtDesc(Long userId, Pageable pageable);

    /**
     * 根据用户ID获取最近编辑的便签
     */
    List<Note> findTop10ByUserIdAndIsDeletedFalseOrderByUpdatedAtDesc(Long userId);

    /**
     * 根据用户ID获取最近收藏的便签
     */
    List<Note> findTop10ByUserIdAndIsFavoriteTrueAndIsDeletedFalseOrderByUpdatedAtDesc(Long userId);

    /**
     * 根据ID和用户ID查找便签
     */
    Optional<Note> findByIdAndUserIdAndIsDeletedFalse(Long id, Long userId);

    /**
     * 统计用户便签数量
     */
    long countByUserIdAndIsDeletedFalse(Long userId);

    /**
     * 统计用户收藏便签数量
     */
    long countByUserIdAndIsFavoriteTrueAndIsDeletedFalse(Long userId);

    /**
     * 根据文件夹ID统计便签数量
     */
    long countByFolderIdAndIsDeletedFalse(Long folderId);

    /**
     * 根据用户ID查找有提醒时间的便签（分页）
     */
    Page<Note> findByUserIdAndReminderTimeIsNotNullAndIsDeletedFalseOrderByUpdatedAtDesc(Long userId, Pageable pageable);
}
